package com.atguigu.lease.model.utils;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.SignatureException;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

//@Configuration
//@ConfigurationProperties
public class JwtUtil {
    //当前工具类 web-admin 和web-app 都需要使用 配置就写在工具类中
    static String secretKey = "1234567890qazwsxedcrfvtgbyhnujmik2213wrewrw4234234235werwrewtesdfsfsfsafsdfdsafsa";
    static long expireTime = 7 * 24 * 60 * 60 * 1000;
    private JwtUtil() {}//私有构造器，避免用户手动创建对象
    //2、解析jwt
    public static Map<String,Object> parseJwt(String token){

        try {
            Claims claims = (Claims) Jwts.parser()
                .setSigningKey(secretKey)
                .parse(token)
                .getBody();
            String username = claims.get("username", String.class);
            String avatarUrl = claims.get("avatarUrl", String.class);
            Long userId = claims.get("userId", Long.class);

            Map<String,Object> map = new HashMap<>();
            map.put("name",username);
            map.put("avatarUrl",avatarUrl);
            map.put("userId",userId);
            return map;
        } catch (ExpiredJwtException e) {
            throw new RuntimeException("登录状态失效，请重新登录");
        } catch (MalformedJwtException e) {
            throw new RuntimeException("token格式错误");
        } catch (SignatureException e) {
            throw new RuntimeException("token验签失败");
        } catch (IllegalArgumentException e) {
            throw new RuntimeException("非法请求");
        } catch (Exception e) {
            throw new RuntimeException("登录状态异常，请重新登录");
        }
    }

    //1、创建jwt
    public static String createJwt(Long userId , String name , String avatarUrl){


        String compact = Jwts.builder()
                //头
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                //载荷
                .setExpiration(new Date(System.currentTimeMillis() + expireTime))
                .claim("userId", userId)//登录成功的用户id
                .claim("username", name) //登录成功的用户账号
                .claim("avatarUrl", avatarUrl) //登录成功用户的头像
                .compressWith(CompressionCodecs.GZIP) //jwt字符串响应给前端时 压缩处理，减少带宽的占用，提高传输效率 但是占用了额外的CPU资源
                .signWith(SignatureAlgorithm.HS256, secretKey)
                .compact();



        return compact;
    }
}